package org.ingeniart.siec.service;

import java.util.List;
import java.util.logging.Logger;
import javax.enterprise.event.Event;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.persistence.EntityManager;



public abstract class AbstracRegistration<T> {
	
	@Inject
	private Logger log;
	
	@Inject
	private EntityManager em;

	
	private Class<T> modelClass;
	
	public abstract Event<T> getEvent();
	public AbstracRegistration(Class<T> modelClass) {
        this.modelClass = modelClass;
    }
	public void register(T model) throws Exception
	{
		log.info("Registering " + model);
		em.persist(model);
		getEvent().fire(model);
		
		
	}
	
	public void update(T model) throws Exception
	{
		log.info("Updating " + model);
		em.merge(model);
		getEvent().fire(model);
	}
	
	public void destroy(T model) throws Exception
	{
		log.info("Deleting " + model);
		em.merge(model);
		getEvent().fire(model);
	}

	public T find(Object id) {
        return em.find(modelClass, id);
    }

    @SuppressWarnings("unchecked")
	public List<T> findAll() {
        @SuppressWarnings("rawtypes")
		javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(modelClass));
        return em.createQuery(cq).getResultList();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(modelClass));
        javax.persistence.Query q = em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    @SuppressWarnings("unchecked")
	public int count() {
        @SuppressWarnings("rawtypes")
		javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(modelClass);
        cq.select(em.getCriteriaBuilder().count(rt));
        javax.persistence.Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
    
    
    public SelectItem[] getSelectItems(boolean selectOne)
    {
    	List<?> entities = findAll();
    	int size = selectOne ? entities.size() + 1 : entities.size();
        SelectItem[] items = new SelectItem[size];
        int i = 0;
        if (selectOne) {
            items[0] = new SelectItem("", "---");
            i++;
        }
        for (Object x : entities) {
            items[i++] = new SelectItem(x, x.toString());
        }
        return items;
    }
    
    
}
